import type { Router, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import { useUserStore } from '@/store';
import { isLogin } from '@/utils/auth';

export default function setupUserLoginInfoGuard(router: Router) {
  // 用于防止循环请求的标志
  let isLoggingOut = false;

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStore();
    
    // 如果当前正在登出过程中，直接放行到登录页
    if (isLoggingOut && to.name !== 'login') {
      next({ name: 'login' });
      return;
    }
    
    // 如果目标是登录页，直接放行
    if (to.name === 'login') {
      next();
      return;
    }

    if (isLogin()) {
      if (userStore.role) {
        next();
      } else {
        try {
          await userStore.info();
          next();
        } catch (error) {
          console.error('获取用户信息失败，重定向到登录页', error);
          
          // 设置登出标志，防止重复请求
          isLoggingOut = true;
          
          await userStore.logout();
          
          // 登出完成后，重置标志
          setTimeout(() => {
            isLoggingOut = false;
          }, 1000);
          
          next({
            name: 'login',
            query: {
              redirect: to.name,
              ...to.query,
            } as LocationQueryRaw,
          });
        }
      }
    } else {
      next({
        name: 'login',
        query: {
          redirect: to.name,
          ...to.query,
        } as LocationQueryRaw,
      });
    }
  });
}
